import { defineConfig, ConfigEnv, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path' //这个path用到了上面安装的@types/node
import dayjs from 'dayjs'
import pkg from './package.json'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver, AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import viteCompression from 'vite-plugin-compression'
import UnoCSS from 'unocss/vite'
import iconsResolver from 'unplugin-icons/resolver'
import qiniuConfig from './qiniu/config'
import viteFunctionQiniuOss from './qiniu/vite-function-qiniu-oss'

const __APP_INFO__ = {
  pkg,
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
}

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  const isBuild = command === 'build'
  console.log(isBuild)
  const root = process.cwd()
  // 环境变量
  const env: Record<string, string> = loadEnv(mode, root, ['VITE_', 'APP_', 'REQUEST_', 'SOCKET_'])
  console.log('******环境变量******', env)
  console.log(
    isBuild && env.VITE_APP_CDN === 'enable'
      ? `${qiniuConfig[mode].domain}/${qiniuConfig.uploadPath}/`
      : env.VITE_BASE_URL
  )
  const vitePlugins = [
    vue(),
    UnoCSS(),
    AutoImport({
      // 目标文件
      include: [
        /.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /.vue$/,
        /.vue?vue/, // .vue
        /.md$/ // .md
      ],
      imports: ['vue', 'vue-router'],
      resolvers: [
        ElementPlusResolver(),
        iconsResolver({
          prefix: 'Icon'
        })
      ],

      dts: './auto-imports.d.ts', // 安装好依赖后，重新运行编译即可自动在根目录下生成此声明文件
      eslintrc: {
        enabled: true, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      }
    }),
    Components({
      resolvers: [
        ElementPlusResolver(),
        AntDesignVueResolver({
          importStyle: false // css in js
        })
      ]
    }),
    {
      ...viteCompression({
        verbose: true,
        disable: false,
        filter: (file: string) => {
          console.info(file)
          return true
        }, // 那些资源不压缩
        threshold: 10240, // 体积大于 threshold 才会被压缩,单位 b
        deleteOriginFile: false, // 压缩后是否删除源文件
        ext: '.gz', // .gz, .br
        algorithm: 'gzip', // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        success: () => {
          if (isBuild && env.VITE_APP_CDN === 'enable') viteFunctionQiniuOss(true, mode, env.VITE_OUTPUT_DIR) // 七牛CDN上传
        }
      }),
      apply: 'build'
    }
  ]
  return {
    root,
    envDir: path.resolve(__dirname, './'),
    base:
      isBuild && env.VITE_APP_CDN === 'enable'
        ? `${qiniuConfig[mode].domain}/${qiniuConfig.uploadPath}/`
        : env.VITE_BASE_URL,
    publicDir: path.resolve(__dirname, './public'),
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
      __APP_VERSION__: JSON.stringify(env.APP_VERSION)
    },
    envPrefix: 'VITE_',
    plugins: vitePlugins,
    //这里进行配置别名
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'), // @代替src
        '#': path.resolve(__dirname, 'types') // #代替types
      }
    },
    server: {
      host: '0.0.0.0',
      port: 8080,
      open: true,
      https: false,
      proxy: {
        '/api': {
          target: 'http://kong.dev.whalepms.com:8000',
          changeOrigin: true,
          ws: true,
          rewrite: (path: string) => path.replace(/^\/api/, '')
        }
      },
      strictPort: false, // 设为true时端口被占用则直接退出，不会尝试其他可用的端口
      hmr: true // 禁用或配置HMR连接（热更新是否开启）
    },
    build: {
      target: 'modules',
      minify: 'esbuild',
      outDir: `${env.VITE_OUTPUT_DIR}`,
      chunkSizeWarningLimit: 1024 * 30,
      terserOptions: {
        compress: {
          keep_infinity: Boolean(env.VITE_DROP_CONSOLE),
          drop_console: Boolean(env.VITE_DROP_CONSOLE),
          drop_debugger: Boolean(env.VITE_DROP_CONSOLE)
        }
      },
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: ['vue', 'vue-router'],
            elementIcons: ['@element-plus/icons-vue']
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/styles/index.scss";'
        }
      }
    }
  }
})
